/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2p.raca.Client;


import java.net.ServerSocket;
import java.io.*;
import java.net.Socket;

/**
 *
 * @author p
 */
public class ClientFileSender extends Thread {
    
    private ServerSocket servsock = null;
    private Socket sock;
    String hostname;
    int size;
    int port;
    String nome;
    public ClientFileSender(String nome)
    {
        this.nome=nome;
         try {
            servsock = new ServerSocket(5055);
        } catch (IOException ex) {
        }
        hostname = servsock.getInetAddress().getHostName();
    }
    
  
    private void sendFile(String fileName) throws IOException
    {
         // create socket

      Socket sok = servsock.accept();
      int offset=0;
      // sendfile
      File myFile = new File (fileName);
      
      byte [] mybytearray  = new byte [1024];
      
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      OutputStream os = sok.getOutputStream();
        long start = System.nanoTime();    
        
        
          while (bis.available()>0)
          {
               int byteread = bis.read(mybytearray,0,1024);
                  os.write(mybytearray,0,byteread);
                  os.flush();
                  offset+=byteread; 
              offset = offset + 1025;
              
          }
          long elapsedTime = System.nanoTime() - start;
          System.out.println("Tempo gasto para enviar o arquivo: "+ myFile.getName()+ " foi: " + elapsedTime);
      sok.close();
      servsock.close();
    }
    
    @Override
    public void run()
    {
        try {
            sendFile(this.nome);
        } catch (IOException ex) {
        }
    }


    
}
